﻿using CSCommonUtils;
using CsharpHttpHelper;
using FX_API.Factory;
using FX_API.Models;
using FX_API.Request;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FX_API.Request
{
    public class FXCommonQueryRequest<T> : FXBasicRequest
    {
        public delegate void HttpRespErrHandler(CallRoot<T> response, Data queryData);

        public HttpRespErrHandler httpRespErrHandler;

        public override string url { get; set; }

        public List<T> GetAllData(string apiName, List<OrdersItem> orderRules, List<string> fieldProjection, List<FiltersItem> filterRules)
        {
            List<T> dataList = new List<T>();
            int limit = 100;
            int offset = 0;
            List<T> tmpList;

            do
            {
                var searchData = QueryModelFactory.CreateQuerySearchData(limit, offset, apiName, orderRules, fieldProjection, filterRules);
                var queryInfo = QueryModelFactory.CreateQueryInfoWithData(searchData);
                tmpList = new List<T>();
                url = queryInfo.data.dataObjectApiName.EndsWith("__c") ? FenxiangAPI.customizedQueryURL : FenxiangAPI.presetQueryURL;   // 如果以"__c"结尾则为自定义的接口，否则为预设接口，需请求不同的url

                try
                {
                    var response = SendQueryRequest(queryInfo);
                    CallRoot<T> respObj = JsonConvert.DeserializeObject<CallRoot<T>>(response.Message);
                    if (!response.IsSucess)
                    {
                        httpRespErrHandler.Invoke(respObj, queryInfo.data);
                        break;
                    }
                    tmpList = respObj.data.dataList;

                    foreach (T item in tmpList)
                    {
                        dataList.Add(item);
                    }

                }
                catch (Exception ex)
                {
                    exceptionHandler.Invoke(ex);
                }

                offset += limit;
            } while (tmpList.Count != 0);

            return dataList;
        }

        /// <summary>
        /// todo: 暂时留在这儿，测试过父类的SendRequest之后删除
        /// </summary>
        /// <param name="queryInfo"></param>
        /// <returns></returns>
        public ResultMessage SendQueryRequest(FXQueryInfo queryInfo)
        {
            HttpItem httpItem = new HttpItem()
            {
                URL = url,
                ContentType = "application/json",
                Accept = "application/json",
                Method = "POST",
                Encoding = Encoding.UTF8,
                Postdata = JsonConvert.SerializeObject(queryInfo)
            };

            var result = helper.GetHtml(httpItem);

            if (result.StatusCode != System.Net.HttpStatusCode.OK) return new ResultMessage() { IsSucess = false, Message = result.Html };
            return new ResultMessage() { IsSucess = true, Message = result.Html };
        }

        public void DEFAULT_HTTP_ERR_HANDLER(CallRoot<T> response, Data queryData)
        {
            Console.WriteLine(string.Format("Err occurs when fx common query [{0}]", response.errorMessage));
        }

        public void DEFAULT_EXCEPTION_HANDLER(Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
        }
    }
}
